package com.powermanagertest;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class Myservice extends Service {
    private final String TAG = "Myservice";

    public static final String TIME_KEY = "key";

    private String SDDIR = "test";
    public static int[] times = { 5, 10, 20 };

    FileService mFileService;

    double i = 100;
    int busyTime = 20;
    int idleTime = busyTime;
    boolean isStart = true;

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        mFileService = FileService.getIntance(this, SDDIR);
    }

    @Override
    public void onStart(Intent intent, int startId) {
        // TODO Auto-generated method stub
        super.onStart(intent, startId);
        int time = times[intent.getExtras().getInt(TIME_KEY)];
        if (time != 0) {
            idleTime = time;
        }
        Log.v("xxx", "time===" + time);
        isStart = true;
        run();
        run();
    }

    private void run() {
        new Thread() {
            public void run() {
                long startTime = 0;
                while (isStart) {
                    startTime = System.currentTimeMillis();
                    // busy loop
                    while ((System.currentTimeMillis() - startTime) <= busyTime) {
                        double d = cpuRun();
                        String text = new String(d + "");
                        inputFile(text);
                    }
                    try {
                        Thread.sleep(idleTime);
                    } catch (InterruptedException e) {
                        System.out.println(e);
                    }
                }
            };
        }.start();
    }

    private double cpuRun() {
        java.util.Random random = new java.util.Random();
        double i = Math.random() * 1000;
        double j = Math.random();
        double r = (random.nextDouble() * i) / j;
        return r;
    }

    private void inputFile(String text) {
        try {
            mFileService.save(SDDIR, text);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        isStart = false;
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

    class WorkThread extends Thread {
        @Override
        public void run() {

        }
    }

}
